package cn.yuysaln.domain.strategy.service.rule.filter.impl;

import cn.yuysaln.domain.strategy.model.entity.RuleActionEntity;
import cn.yuysaln.domain.strategy.model.entity.RuleMatterEntity;
import cn.yuysaln.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.yuysaln.domain.strategy.repository.IStrategyRepository;
import cn.yuysaln.domain.strategy.service.annotation.LogicStrategy;
import cn.yuysaln.domain.strategy.service.rule.filter.ILogicFilter;
import cn.yuysaln.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import cn.yuysaln.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * 黑名单过滤器的具体实现
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_BLACKLIST)
public class RuleBlackListLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {
    @Resource
    private IStrategyRepository repository;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-黑名单 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());

        String userId = ruleMatterEntity.getUserId();

        //查询黑名单  例如：100：user01,user02...
        String ruleValue=  repository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(), ruleMatterEntity.getAwardId(), ruleMatterEntity.getRuleModel());
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        //黑名单只能抽到的奖品id
        int awardId = Integer.parseInt(splitRuleValue[0]);
        //具体黑名单成员
        String[] userBlackIds = splitRuleValue[1].split(Constants.SPLIT);

        //查看当前Matter中的user是否在黑名单，在黑名单就生成相应的接管Action
        for (String userBlackId : userBlackIds) {
            if (userId.equals(userBlackId)){
                return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                        .ruleModel(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode())
                        .data(RuleActionEntity.RaffleBeforeEntity.builder()   //内部类的构造
                                .strategyId(ruleMatterEntity.getStrategyId())
                                .awardId(awardId)
                                .build())
                        .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                        .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                        .build();

            }
        }

        //不在黑名单就放行
        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }
}
